<template>
  <div class="code">
    <el-header class="header">
      <div class="logoBox" @click="$router.push('/')">
        <img src="../assets/logo.png" alt=""/>
        <h1>互开组件库</h1>
      </div>

      <!--      右侧加个头像-->
      <div class="infoBox">
        <!--头像旁添加上传组件按钮 点击弹框上传文件-->
        <div class="upload">
          <el-button type="primary" icon="el-icon-plus" @click="dialogVisible = true">添加组件</el-button>
          <el-dialog title="添加组件" :visible.sync="dialogVisible" width="70%">
            <!--          添加2列的form表单-->
            <el-form :model="form" ref="ruleForm" :rules="rules" label-width="80px">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="组件名称" required prop="name">
                    <el-input v-model="form.name"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="组件类型" required prop="categoryId">
                    <el-select v-model="form.categoryId" placeholder="请选择">
                      <el-option
                          v-for="item in categoryList"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="组件作者" required prop="author">
                    <el-input v-model="form.author"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="组件版本" required prop="lastVersion">
                    <el-input-number v-model="form.lastVersion" :min="1" label="描述文字"></el-input-number>
                  </el-form-item>
                </el-col>

              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="组件描述" required prop="noteSimple">
                    <el-input type="textarea" maxlength="200" v-model="form.noteSimple"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="代码文件(仅zip文件)">
                    <el-upload
                        class="upload-demo"
                        :multiple="false"
                        accept="zip"
                        action="api/file/upload" :data="{params:JSON.stringify({categoryId:form.categoryId})}">
                      <!--          :on-preview="handlePreview"-->
                      <!--          :on-remove="handleRemove"-->
                      <!--          :before-upload="beforeAvatarUpload"-->
                      <!--          :on-success="handleAvatarSuccess"-->
                      <!--          :file-list="fileList"-->
                      <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
               <Editor :value.sync="initContent"></Editor>

              </el-row>
            </el-form>
            <!--            加点高度-->

            <div style="height: 20px"></div>

            <div slot="footer" class="dialog-footer">
              <el-button size="small" type="warning" @click="dialogVisible = false">取 消</el-button>
              <el-button size="small" type="primary" @click="addModule('ruleForm')">确 定</el-button>
            </div>
          </el-dialog>
        </div>
        <!--    <el-dropdown-->
        <!--        class="avatar-container right-menu-item hover-effect"-->
        <!--        trigger="click">-->
        <!--      <div class="avatar-wrapper">-->
        <!--        <el-avatar :size="40" :src="userInfo.avatar" alt=""></el-avatar>-->
        <!--        <i class="el-icon-caret-bottom"/>-->
        <!--      </div>-->
        <!--&lt;!&ndash;      <el-dropdown-menu slot="dropdown">&ndash;&gt;-->
        <!--&lt;!&ndash;        <router-link to="/profile"></router-link>&ndash;&gt;-->
        <!--&lt;!&ndash;        <router-link v-if="isToken" to="/profile">&ndash;&gt;-->
        <!--&lt;!&ndash;          <el-dropdown-item>个人中心</el-dropdown-item>&ndash;&gt;-->
        <!--&lt;!&ndash;        </router-link>&ndash;&gt;-->
        <!--&lt;!&ndash;        <router-link v-if="isToken" to="/profile">&ndash;&gt;-->
        <!--&lt;!&ndash;          <el-dropdown-item>退出登录</el-dropdown-item>&ndash;&gt;-->
        <!--&lt;!&ndash;        </router-link>&ndash;&gt;-->
        <!--&lt;!&ndash;      </el-dropdown-menu>&ndash;&gt;-->
        <!--    </el-dropdown>-->
      </div>

    </el-header>
    <div class="main">
      <split-pane @resize="resize" :min-percent='15' :default-percent='15' split="vertical">
        <template slot="paneL">
          <div class="left">
            <el-collapse v-model="activeName" accordion>
              <el-collapse-item v-for="item in categoryList" :title="item.name" :name="item.id" :key="item.id">
                <ul class="list-box">
                  <li v-for="i in item.moduleListVos" :key="i.id" @click="loadModuleDetail(i.id)">
                    {{ i.name }}
                  </li>
                </ul>
              </el-collapse-item>
            </el-collapse>
          </div>
        </template>
        <template slot="paneR">
          <div class="title">
            <h3>{{ moduleDetail.name }}</h3><br>
            <h5>{{ moduleDetail.noteSimple }}</h5> <br>
            当前版本： {{ moduleDetail.lastVersion }}
            <el-popover
                placement="bottom"
                width="400"
                trigger="click">
              <el-table :data="gridData">
                <el-table-column width="150" property="date" label="日期"></el-table-column>
                <el-table-column width="100" property="name" label="姓名"></el-table-column>
                <el-table-column width="300" property="address" label="地址"></el-table-column>
              </el-table>
              <el-button slot="reference" type="warning">历史版本</el-button>
            </el-popover>

            作者： {{ moduleDetail.author }}
            <el-link :href="moduleDetail.fileDownloadUrl" :underline="false" style="margin-left:15px">
              <el-button size="mini" type="success">源码下载</el-button>
            </el-link>
            <!--               添更新组件按钮-->
            <el-button size="mini" type="primary" @click="dialogVisible = true">更新组件</el-button>
          </div>
          <ul class="tabs-box">
            <li class="tabs-item"
                :class="{active:activeTabsName===item.value}"
                v-for="item in tabList" :key="item.label"
                @click="handleClick(item.value)"
            >{{ item.label }}
            </li>
          </ul>
          <div class="code-box" v-show="activeTabsName==='first'">
            <div class="local-quill-editor">
              <Editor :value.sync="content" :disabled="true" :is-toolbar="false"></Editor>
            </div>
          </div>
          <div class="code-box" v-show="activeTabsName==='second'">
            <split-pane split="vertical" :min-percent='18' :default-percent='18'>
              <template slot="paneL">
                <div class="tree-box">
                  <el-tree :data="tree" :props="defaultProps" node-key="name" :default-expanded-keys="expandedKeys"
                           @node-click="handleNodeClick"></el-tree>
                </div>
              </template>
              <template slot="paneR">
                <iframe
                    id="codeFrame"
                    ref="iframes"
                    style="display:none"
                ></iframe>
                <div class="code-inner">
                  <myCode
                      v-if="values != '' && isshow"
                      :value="values"
                      :language="language"
                  />
                </div>

              </template>
            </split-pane>
          </div>

        </template>
      </split-pane>

    </div>
  </div>
</template>

<script>
import splitPane from "vue-splitpane"
import {categoryList} from "@/sdk/modules/category";
import {moduleDetail, moduleList} from "@/sdk/modules/module";
import Code from "@/views/preview/code";
import Editor from "@/components/Editor.vue";

export default {
  name: "Code",
  components: {
    'split-pane': splitPane,
    myCode: Code,
    Editor
  },
  data() {
    return {
      initContent: '',
      content: '请添加正文',
      model: '',
      activeTabsName: 'first',
      form: {
        name: '',
        lastVersion: 1,
      },
      userInfo: {
        name: '测试',
        avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
      },
      dialogVisible: false,
      tabList: [
        {label: '详情', value: 'first'},
        {label: '代码', value: 'second'},
      ],
      gridData: [{
        date: '2016-05-02',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1518 弄'
      }, {
        date: '2016-05-04',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1518 弄'
      }, {
        date: '2016-05-01',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1518 弄'
      }, {
        date: '2016-05-03',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1518 弄'
      }],
      activeTabName: 'first',
      activeName: "1",
      tree: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      expandedKeys: [],
      categoryList: [],
      moduleDetail: {},
      moduleList: [],
      isshow: true,
      values: "",
      language: "",
      iframe: null,
      rules: {
        name: [
          {required: true, message: '请输入组件名称', trigger: 'blur'},
          {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
        ],
        categoryId: [
          {required: true, message: '请选择组件分类', trigger: 'change'}
        ],
        lastVersion: [
          {required: true, message: '请输入组件代码', trigger: 'blur'}
        ],
        noteSimple: [
          {required: true, message: '请输入组件描述', trigger: 'blur'}
        ],
        author: [
          {required: true, message: '请输入作者', trigger: 'blur'}
        ],

      }
    }
  },
  created() {
    this.loadCategoryList();
  },
  mounted() {
  },
  methods: {
    // 失去焦点事件
    onEditorBlur(e) {
      console.log('onEditorBlur: ', e)
    },
    // 获得焦点事件
    onEditorFocus(e) {
      // e.enable(false);
      console.log('onEditorFocus: ', e)
    },
    // 内容改变事件
    onEditorChange(e) {
      console.log('onEditorChange: ', e)
      console.log('onEditorChange: ', e.html)

    },
    resize() {

    },
    loadCategoryList() {
      this.categoryList = [];
      categoryList({}).then(res => {
        this.categoryList = res.data
        this.activeName = this.categoryList[0].id
        this.loadModuleDetail(this.categoryList[0].moduleListVos[0].id)

      });
    },
    loadModuleDetail(id) {
      this.moduleDetail = {};
      this.tree = [];
      moduleDetail({id: id}).then(res => {
        this.moduleDetail = res.data
        this.tree = res.data.fileTree.children;
        this.expandedKeys = [this.tree[0].name]
        this.content = this.moduleDetail.note
        this.handleNodeClick(this.tree[0].children[0])
      });
    },
    loadModuleList() {
      this.moduleList = [];
      moduleList({categoryId: this.activeName}).then(res => {
        this.moduleList = res.data
      });
    },
    addModule(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!');
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    showModuleDetail(row) {
      this.loadModuleDetail(row.id)
    },
    arraySpanMethod() {

    },
    // categoryChange(row) {
    //   this.loadModuleList(this.activeName);
    // },
    handleNodeClick(row) {
      if (!row.directory) {
        this.isshow = false;
        if (!this.iframe) {
          this.iframe = this.$refs.iframes;
        }
        let _this = this;
        let path = row.path.split(".");
        this.language = path[path.length - 2];
        this.iframe.src = `${row.path}`;
        if (this.iframe.attachEvent) {
          this.iframe.attachEvent("onload", function () {
            //其它处理代码
          });
        } else {
          this.iframe.onload = function () {
            //其它处理代码
            _this.renderIframe();
          };
        }
      }
    },
    handleTabClick(tab, event) {
      console.log(tab, event);
    },
    handleClick(val) {
      this.activeTabsName = val
    },
    renderIframe() {
      const iwindow = this.iframe.contentWindow;
      const idoc = iwindow.document;
      this.article_type = idoc.body.innerHTML;
      this.values = this.htmlDecodeByRegExp(
          idoc.body.innerHTML.replace(/<.*?>/gi, "")
      );
      this.isshow = true;
    },
    htmlDecodeByRegExp(str) {
      var temp = "";
      if (str.length == 0) {
        return "";
      }
      temp = str.replace(/&amp;/g, "&");
      temp = temp.replace(/&lt;/g, "<");
      temp = temp.replace(/&gt;/g, ">");
      temp = temp.replace(/&nbsp;/g, " ");
      temp = temp.replace(/&#39;/g, "'");
      temp = temp.replace(/&quot;/g, '"');
      return temp;
    },
  }
}
</script>

<style scoped lang="less">
.header {
  background: -webkit-linear-gradient(top, #ffffff, #ebf6fe);
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;

  .logoBox {
    display: flex;
    align-items: center;

    & > img {
      width: 32px;
      height: 32px;
      margin-right: 10px;
    }

    & > h1 {
      font-size: 18px;
      margin-right: 10px;
    }
  }

  .infoBox {
    display: flex;
    align-items: center;

    & > img {
      width: 32px;
      height: 32px;
      margin-right: 10px;
    }

    & > span {
      font-size: 14px;
      margin-right: 10px;
    }
  }
}

.main {
  height: calc(100vh - 80px);

  .left {
    padding: 0 10px;
    width: 100%;
    height: 100%;
    overflow-y: scroll;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .list-box {
      li {
        cursor: pointer;
        padding: 10px;
        border-bottom: 1px solid #ebeef5;

        &:hover {
          background: #f5f7fa;
        }
      }
    }

    /deep/ .el-collapse-item__content {
      padding: 0;
    }
  }

  .title {
    height: 120px;
    padding: 10px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .tabs-box {
    display: flex;
    align-items: center;
    height: 40px;
    box-sizing: border-box;
    background: #fff;
    border-bottom: 1px solid #ebeef5;

    .tabs-item {
      cursor: pointer;
      padding: 0 20px;
      height: 100%;
      line-height: 40px;
      color: #606266;
      border-bottom: 2px solid #fff;

      &.active {
        color: #409eff;
        border-bottom: 2px solid #409eff;
      }
    }

  }

  .code-box {
    height: calc(100% - 120px - 40px);
    //padding: 10px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    overflow-y: scroll;
    box-sizing: border-box;
  }

  .tree-box {
    width: 100%;
    height: 100%;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-right: 10px;
    //padding: 10px;
    overflow: auto;
  }

  .code-inner {
    width: 100%;
    height: 100%;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 10px;
    overflow-y: scroll;
    box-sizing: border-box;
  }
}

.editor {
  //height: calc(100vh - 290px  );
  height: 200px;
}

.readoletEditor {
  //height: calc(100vh - 290px  );
  height: 100%;
}
</style>
